package com.fjnu.dao.impl;

import com.fjnu.dao.TagDao;
import com.fjnu.entity.Article;
import com.fjnu.entity.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class TagDaoImpl implements TagDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Tag tag) {
        String sql = "INSERT INTO tb_tag (name,create_time,update_time) VALUES (?,?,?)";
        int result = jdbcTemplate.update(sql,
                tag.getName(),
                tag.getCreateTime(),
                tag.getUpdateTime());
        return result > 0 ? 1 : 0;

    }

    @Override
    public int insertArticleTag(Integer articleId, Integer tagId) {
        String sql = "INSERT INTO tb_article_tag (article_id,tag_id) VALUES (?,?)";
        int result = jdbcTemplate.update(sql,
                articleId,
                tagId);
        return result ;
    }

    @Override
    public List<Tag> list() {
        String sql = "SELECT * FROM tb_tag";
        return jdbcTemplate.query(sql, new TagRowMapper());
    }

    @Override
    public int delete(Integer tagId) {
        String sql = "DELETE FROM tb_tag WHERE id = ?";
        return jdbcTemplate.update(sql, tagId);
    }
    private static class TagRowMapper implements RowMapper<Tag> {
        @Override
        public Tag mapRow(ResultSet rs, int rowNum) throws SQLException {
            Tag tag = new Tag();
            tag.setId(rs.getInt("id"));
            tag.setName(rs.getString("name"));
            tag.setCreateTime(rs.getTimestamp("create_time"));
            tag.setUpdateTime(rs.getTimestamp("update_time"));
            return tag;
        }
    }
}
